const app = getApp();
const { post } = require('../../utils/request');

Page({
  data: {
    username: '',
    password: '',
    isLoading: false
  },

  onLoad() {
    this.checkLoginStatus();
  },

  onShow() {
    this.checkLoginStatus();
  },

  // 检查登录状态
  async checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (token ) {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  // 账号密码登录
  async handleLogin() {
    const { username, password } = this.data;
    
    if (!username || !password) {
      wx.showToast({
        title: '请输入用户名和密码',
        icon: 'none'
      });
      return;
    }

    try {
      this.setData({ isLoading: true });

      const res = await post('/users/login', {
        username,
        password
      });

      this.setData({ isLoading: false });

      if (res.token) {
        // 保存登录状态
        wx.setStorageSync('token', res.token);
        wx.setStorageSync('userInfo', res.user)
        app.globalData.userInfo = res.user;
        app.globalData.hasLogin = true;

        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });

        // 跳转到首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      }
    } catch (error) {
      this.setData({ isLoading: false });
      wx.showToast({
        title: error.message || '登录失败',
        icon: 'none'
      });
    }
  },

  // 微信登录
  async handleWechatLogin(e) {
    if (!e.detail.userInfo) {
      wx.showToast({
        title: '您已取消授权',
        icon: 'none'
      });
      return;
    }

    try {
      this.setData({ isLoading: true });

      // 获取微信登录凭证
      const loginRes = await wx.login();
      
      if (!loginRes.code) {
        throw new Error('获取微信登录凭证失败');
      }

      // 调用后端微信登录接口
      const res = await post('/users/wechat-login', {
        code: loginRes.code,
        userInfo: e.detail.userInfo
      });

      this.setData({ isLoading: false });

      if (res.token) {
        // 保存登录状态
        wx.setStorageSync('token', res.token);
        app.globalData.userInfo = res.user;
        app.globalData.hasLogin = true;

        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });

        // 跳转到首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      }
    } catch (error) {
      this.setData({ isLoading: false });
      wx.showToast({
        title: error.message || '微信登录失败',
        icon: 'none'
      });
    }
  },

  navigateToRegister() {
    wx.navigateTo({
      url: '/pages/register/register'
    });
  }
}); 